import { PureComponent } from "react";
import { Button, Modal,ActivityIndicator,InputItem,Tabs,SearchBar,Carousel,PullToRefresh,ListView } from "antd-mobile"
import { connect } from 'dva';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import MToast from '../../components/Util/MToast';
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import { Row, Col } from 'antd';
import ReactDOM from 'react-dom';
import Macy from 'macy';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
let pageIndex = 0;
function genData(pIndex,NUM_ROWS) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}
@connect(() => {
  return ({

  })
})
export default class categoryPage extends PureComponent{
  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      dataSource,
      TabData:[],
      TabDataList:[],
      goodsItem:[],
      newsList:[],
      pages:{
        pageNum:1,
        pageSize:20
      },
      hasMore: true,
      refreshing: true,
      isLoading: true,
      height: document.documentElement.clientHeight * 3 / 4,
      useBodyScroll: false,
      onSearch:false,
      IsImage:false,
      masonry:false
    }
  }
  componentDidUpdate() {
  }
  componentDidMount() {
    const hei = document.documentElement.clientHeight -260;
    console.log(hei,document.documentElement.clientHeight,ReactDOM.findDOMNode(this.lv).parentNode.offsetTop)
    setTimeout(() => {
      this.setState({

        height: hei,
      });
    }, 600);
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
    console.log(location.search)
    const query = location.search;
    console.log(query)
    const arr = query.split('&') // ['?s=', 'f=7']
    console.log(arr)
    const code = arr[0].substr(6) // '1'
    localStorage.setItem("code",code)
    const name = arr[1].substr(5) // '7'
    console.log(code,name)
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: decodeURI(name),
        path: location.pathname + location.search
      }
    });
    this.handleCategoryList(code)
    this.handleGoodsList(code);

  }
  getMacy = () => {
    console.log("33333333333333333333333")
    var macyInstance = Macy({
        container: '.list-view-section-body', // 图像列表容器
        trueOrder: false,
        waitForImages: false,
        useOwnImageLoader: false,
        debug: true,
        margin: { x: 13, y: 4 },    // 设计列与列的间距
        columns: 2,    // 设置列数
      })

  }
  handleGoodsList=(code)=>{
    let {dispatch,location} = this.props;
    let {goodsItem} = this.state;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_category_goods_list_search",
          params: [
            {
              "key":"category_id",
              "value":code
            }
          ],
          _c: "app_category_goods_list_search"
        },
        callback: (result) => {
          let { data } = result;
          this.rData = genData(0,data.length);
          this.setState({
            goodsItem:data,
            dataSource: this.state.dataSource.cloneWithRows(this.rData),
            isLoading: false,
          })
          if(data.length==0){

          }else{
            this.getMacy()
          }
          console.log(goodsItem,data);

        }
      }
    });
  }

  onRefresh = () => {
    this.setState({ refreshing: true, isLoading: true });
    // simulate initial Ajax
    setTimeout(() => {
      this.rData = genData(0,this.state.goodsItem.length);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        refreshing: false,
        isLoading: false,
      });
    }, 600);
    if(this.state.goodsItem.length==0){

    }else{
      this.getMacy()
    }

  };
  onScroll=()=>{
    this.getMacy()
  }

 objToArray=(obj)=>{
    var array = [];

    for(var key in obj){

      array.push(obj[key]);

    }

    return array;

  }
  onEndReached = (event) => {
    // this.getMacy()
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
      console.log('reach end', event);
      this.setState({ isLoading: true });

        this.rData = { ...this.rData, ...genData(++pageIndex) };
        this.setState({
          dataSource: this.state.dataSource.cloneWithRows(this.rData),
          isLoading: false,
        });
    this.getMacy()
   console.log(this.objToArray(this.rData),this.objToArray(this.rData).length)
console.log( this.rData,this.rData.length,pageIndex)

  }

  handleCategoryList=(code)=>{
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=new_category_list_show_node",
          params: [
            {
              "key":"parent_id",
              "value":code
            }
          ],
          _c: "new_category_list_show_node"
        },
        callback: (result) => {
          let { data } = result;


          var result =[];
          for(var i=0;i<data.length;i+=4){
            result.push(data.slice(i,i+4))
          }
          console.log(result)
          this.setState({
            TabData:data,
            TabDataList:result
          })

        }
      }
    });
  }
  handleCategory=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/category_page1?code="+i.id+"&name="+i.name }, isReplace: false })
  }
  categoryList(){
    let {TabDataList} = this.state;
    if (!TabDataList || TabDataList.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else{
      return(
        <Carousel
          autoplay={false}
          infinite={false}
          dots={false}
        >

          {TabDataList.map((i,k)=>(
            <Row>
              {i.map((i,k)=>(
                <Col span={6} key={i.code} style={{padding:'0 2%'}} onClick={(e)=>{this.handleCategory(e,i)}}>
                  <img src={handleOSS(i.img_url)} style={{width:'100%',height:'73px'}}/>
                  <p  className="ellipsis4" style={{color:'#303133',marginTop:'10px',width:'100%'}}>{i.name}</p>
                </Col>
              ))}

            </Row>
          ))}


        </Carousel>
      )
    }
  }
  goodList() {
    let { goodsItem} = this.state;


    if (!goodsItem || goodsItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div className="box" style={{paddingBottom:'0%'}}>
          {goodsItem.map((i,k) => (
            <div  key={k} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
              <div onClick={(e)=>{this.handleDetail(e,i)}}>
                <img src={handleOSS(i.img_url)} style={{width:'100%',height:'100%'}}/>

              </div>
              <div style={{overflow:'hidden'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{i.goods_name}</p>
                <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{i.price}</div>
                <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,i) }}>
                  <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                </div>
              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>

          ))}
        </div>

      )
    }
  }
  handleSearchCancel=()=>{
    let {dispatch,location,onSearch} = this.props;
    console.log(location.search)
    const query = location.search;
    console.log(query)
    const arr = query.split('&') // ['?s=', 'f=7']
    console.log(arr)
    const code = arr[0].substr(6) // '1'
    const name = arr[1].substr(5) // '7'
    console.log(code,name)
    this.setState({
      value: '',
      dataSource: this.state.dataSource.cloneWithRows([]),
    });
    this.handleGoodsList(code)
  }
  onChange= (value) => {
    this.setState({ value });
  };
  submit=()=>{
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows([]),
    })
    let {dispatch,location} = this.props;
    let {value,loading,onSearch} = this.state;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_search_goods_list",
          params: [
            {
              key: "keyword",
              value: value
            },
          ],
          _c: "app_search_goods_list"
        },
        callback: (result) => {
          let { data } = result;
          let {loading} = this.state;
          this.rData = genData(0,data.length);
          this.setState({
            goodsItem:data,
            dataSource: this.state.dataSource.cloneWithRows(this.rData),
            isLoading: false,
          })
          if(data.length==0){

          }else{
            this.getMacy()
          }

        }
      }
    });
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id+"&status="+i.status }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    if(	localStorage[MI_APP_CODE + "username"]=="admin"){
      MToast.info(T("您还未登录，请登录后操作",3, null, false));
    }else{
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "cart/add",
            params: [
              {
                key: "goods_id",
                value: i.id
              },
              {
                key: "goods_name",
                value: i.goods_name
              },
              {
                key: "img_url",
                value: i.img_url
              },
              {
                key: "price",
                value: i.price
              },
              {
                key: "quantity",
                value: 1
              }
            ]
          },
          callback: (result) => {
            let { data } = result;
            console.log(data)
            if(data.status=="0"){
              alert("该商品已下架")
            }else{
              MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo),3, null, false);
            }


          }
        }
      })
    }

  }
  handleImageLoaded=()=>{
    let {IsImage} =this.state;
    this.setState({
      IsImage:true
    })
  }
  render(){
    let {dispatch} = this.props;
    let {TabData,TabDataList,IsImage,goodsItem} = this.state;
    const messages = localeData[localStorage.locale];
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
console.log(this.state.dataSource)
      let index = goodsItem.length - 1;
      const row = (rowData, sectionID, rowID) => {
        if (index < 0) {
          index = goodsItem.length - 1;
        }
        const obj = goodsItem[index--];
        console.log(goodsItem,obj);
          return (

            <div style={{marginBottom:'6%'}} >
              <div  key={rowID} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
                <div onClick={(e)=>{this.handleDetail(e,obj)}}>
                  {IsImage?
                    <img src={handleOSS(obj.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                    :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}

                </div>
                <div style={{overflow:'hidden'}}>
                  <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{obj.goods_name}</p>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{obj.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,obj) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

                {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
              </div>


            </div>

        )



      };

    return(
      <IntlProvider
        locale={ localStorage.locale } messages={messages}
      >
      <div style={{background:'#F6F6FC',width:'100%',height:'100%'}}>
        <div style={{paddingTop:'45px',}}> <SearchBar
          placeholder={messages.search}
          maxLength={200}
          onChange={this.onChange}
          onSubmit={value => this.submit(value)}
          onCancel={value=>this.handleSearchCancel(value)}
        /></div>

        <div style={{background:'#fff',padding:'10px',marginBottom:'10px'}}>
          {this.categoryList()}
        </div>
        <ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={() => (<div style={{ padding: 10, textAlign: 'center' }}>
            {this.state.isLoading ? 'Loading...' : 'Loaded'}
          </div>)}
          renderRow={row}
          style={{
            height: this.state.height,
            overflow: 'auto',
            paddingBottom:'4%'
          }}
          pageSize={1}
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={100}
          pullToRefresh={<PullToRefresh
            refreshing={this.state.refreshing}
            onRefresh={this.onRefresh}
          />}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={10}
        />




      </div>
      </IntlProvider>
    )
  }
}
